<?php
/*
# ------------------------------------------------------------------------
# JA Job Board Package
# ------------------------------------------------------------------------
# Copyright (C) 2004-2010 JoomlArt.com. All Rights Reserved.
# @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
# Author: JoomlArt.com
# Websites: http://www.joomlart.com - http://www.joomlancers.com.
# ------------------------------------------------------------------------
*/

jimport ( 'joomla.application.component.model' );
jimport ( 'joomla.filesystem.file' );
JTable::addIncludePath ( JPATH_COMPONENT . DS . 'tables' );

/**
 * @package Joomla
 * @subpackage JobBoard
 */
class JAJobBoardModelJAApplications extends JModel {
	var $_table;
	var $_pagination;
	var $_fieldList = null;
	var $_searchparams;
	var $_fieldListEdit;
	var $_table_name = 'ja_applications';
	
	/**
	 * Return the query is used to retrive all row from database
	 * @return string The query is used 
	 */
	function getItems($where_more = '', $limit = 0, $limitstart = 20) {
		
		global $mainframe, $jbconfig, $option;
		
		$db = JFactory::getDBO ();
		
		$request = $_REQUEST;
		$filter_field_keys = array ();
		if ($request) {
			$filter_field_keys = array_keys ( $request );
		}
		
		$limit = $mainframe->getUserStateFromRequest ( JBCOMNAME . ".jaapplication.limit", 'limit', '20', 'int' );
		$limitstart = $mainframe->getUserStateFromRequest ( JBCOMNAME . ".jaapplication.limitstart", 'limitstart', '0', 'int' );
		
		$db = JFactory::getDBO ();
		
		$search = $mainframe->getUserStateFromRequest ( JBCOMNAME . ".jaapplication.search", 'search', '', 'string' );
		$search = trim ( JString::strtolower ( $search ) );
		
		$this->getFieldList ();
		$this->getEditFieldList ( ' and f.frontend_hidden=0' );
		
		$filter_order = JRequest::getVar ( 'filter_order', 'a.id' );
		$filter_order_Dir = $mainframe->getUserStateFromRequest ( $option . ".jaapplication.filter_order_Dir", 'filter_order_Dir', "DESC", 'word' );
		
		$where = array ();
		
		// just in case filter_order get's messed up
		$join = '';
		$orderby = '';
		$where = "";
		$fields_show = '';
		
		$join_clause_field = array ();
		$join_clause_table = array ();
		$field_temp = array ();
		$subwhere = array ();
		$where_clause = array ();
		
		JB_Admin_Build_where ( $join_clause_table, $join_clause_field, $field_temp, $where_clause, $this->_fieldListEdit, $filter_field_keys, $request, $search );
		
		if ($filter_order) {
			$orderby = $filter_order . ' ' . $filter_order_Dir;
		} else {
			$orderby = " a.id DESC";
		}
		
		foreach ( $join_clause_table as $j => $table ) {
			$join .= "\n $table ";
			if (isset ( $join_clause_field [$j] )) {
				$join .= $join_clause_field [$j];
			}
		}
		
		if ($where_clause) {
			$where = ' AND ' . implode ( ' AND ', $where_clause );
		}
		
		/* Count items */
		$query = "SELECT count(distinct a.id) " . "\n FROM #__$this->_table_name as a" . $join . "\n WHERE 1=1 " . $where . $where_more;
		
		$db->setQuery ( $query ); //echo $db->getQuery();exit;
		$total = $db->loadResult ();
		
		jimport ( 'joomla.html.pagination' );
		$this->_pagination = new JPagination ( $total, $limitstart, $limit );
		
		/* Get all items */
		$query = "SELECT distinct a.id, a.*" . "\n FROM #__$this->_table_name as a" . $join . "\n WHERE 1=1 " . $where . $where_more . "\n ORDER BY " . $orderby . ', a.id desc';
		$db->setQuery ( $query, $limitstart, $limit );
		
		$items = $db->loadObjectList ();
		
		$jconfig = new JConfig ( );
		$timezone = $jconfig->offset;
		$user = JFactory::getUser ();
		
		if ($items) {
			foreach ( $items as $k => $job )
				if (isset ( $job->id )) {
					if ($items [$k]->created_date) {
						if (! $user)
							$job->created_date = generateDate ( $items [$k]->created_date );
						else
							$job->created_date = generateDate ( date ( 'Y-m-d H:i:s', strtotime ( $items [$k]->created_date ) - date ( 'Z' ) + $user->getParam ( 'timezone', $timezone ) * 60 * 60 ) );
					}
					
					if ($this->_fieldList) {
						foreach ( $this->_fieldList as $field ) {
							
							$job->{$field->field_name} = JFilterInput::_decode ( $job->{$field->field_name} );
							
							if ($field->field_type == 'TEXTFIELD') {
								$job->{$field->field_name} = JFilterInput::clean ( $job->{$field->field_name} );
							}
							
							if ($field->is_referred > 0 && $job->{$field->field_name}) {
								
								$values = explode ( ',', $job->{$field->field_name} );
								foreach ( $values as $i => $v ) {
									$values [$i] = $db->Quote ( $v );
								}
								$values = implode ( ',', $values );
								
								$sql = "SELECT {$field->referred_value} " . "\n FROM #__{$field->referred_table} " . "\n WHERE {$field->referred_key} in ($values)";
								$db->setQuery ( $sql );
								$result = $db->loadResultArray ();
								if ($result) {
									$job->{$field->field_name} = implode ( ', ', $result );
								} else {
									$job->{$field->field_name} = '';
								}
							
							} elseif (in_array ( $field->field_type, array ('RADIO', 'SELECT', 'MSELECT' ) ) && $job->{$field->field_name}) {
								
								$values = explode ( ',', $job->{$field->field_name} );
								foreach ( $values as $i => $v ) {
									$values [$i] = $db->Quote ( $v );
								}
								$values = implode ( ',', $values );
								if(!$values) $values=0;
								$field_id = $field->table_name . '_' . $field->field_name;
								
								$sql = "SELECT text " . "\n FROM #__ja_codes " . "\n WHERE value in ($values) and field_id='$field_id' ";
								
								$db->setQuery ( $sql );
								$result = $db->loadResultArray ();
								
								if ($result) {
									$job->{$field->field_name} = implode ( ', ', $result );
								} else {
									$job->{$field->field_name} = '';
								}
							}
						}
						
						$items [$k] = $job;
					}
				}
		}
		return $items;
	
	}
	
	/**
	 * @desc Get all fields that will be displayed on edit form
	 */
	function getEditFieldList($where = '') {
		if (! $this->_fieldListEdit) {
			$this->_fieldListEdit = getEditFieldList ( $this->_table_name );
		}
		return $this->_fieldListEdit;
	}
	
	function getFieldList($where = '') {
		if (! $this->_fieldListEdit) {
			$this->_fieldList = getFieldList ( $this->_table_name, $where );
		}
		
		return $this->_fieldList;
	}
	
	/**
	 * Get field table instance
	 * @return JTable Configuration table object
	 */
	function &_getTable() {
		if ($this->_table == null) {
			$this->_table = &JTable::getInstance ( 'JA_Applications', 'JobBoardTable' );
		}
		
		return $this->_table;
	}
	
	/**
	 * Get page navigator object
	 * @return 
	 */
	function &getPagination() {
		if ($this->_pagination == null) {
			$this->getItems ();
		}
		return $this->_pagination;
	}
	
	/**
	 * Get configuration item
	 * @return JobboardTableJA_resumes Table object
	 */
	function getItem() {
		static $item;
		if (isset ( $item )) {
			
			return $item;
		}
		
		$table = & $this->_getTable ();
		// Load the current item if it has been defined
		$edit = JRequest::getVar ( 'edit', true );
		$cid = JRequest::getVar ( 'cid', array (0 ), '', 'array' );
		JArrayHelper::toInteger ( $cid, array (0 ) );
		
		if ($edit) {
			$table->load ( $cid [0] );
		}
		$item = $table;
		return $item;
	}
	
	function getAppItem() {
		
		static $item;
		if (isset ( $item )) {
			return $item;
		}
		$table = & $this->_getTable ();
		$job_id = JRequest::getVar ( 'job_id', 0 );
		$user = &JFactory::getUser ();
		$db = &JFactory::getDBO ();
		if ($job_id && getCurrentUserType () == JBJOB_SEEKER_USER) {
			$query = "SELECT id FROM #__ja_applications WHERE job_id = " . $job_id . " AND user_id = " . $user->id;
			$db->setQuery ( $query );
			$appid = $db->loadResult ();
			$table->load ( $appid );
		}
		
		$item = $table;
		return $item;
	}
	
	function getListItem_Employer($user_id, $limit, $limitstart) {
		if (! $user_id) {
			$user = JFactory::getUser ();
			$user_id = $user->id;
		}
		$str_job_list = $this->getListJob_Employer ( $user_id );
		$where = " and a.job_id IN (" . $str_job_list . ")";
		$items = $this->getItems ( $where, $limit, $limitstart );
		return $items;
	
	}
	
	function getListJob_Employer($user_id) {
		if (! $user_id) {
			$user = JFactory::getUser ();
			$user_id = $user->id;
		}
		$db = JFactory::getDBO ();
		$query = "SELECT id FROM #__ja_jobs WHERE user_id=$user_id";
		;
		$db->setQuery ( $query );
		$job_list = $db->loadObjectList ();
		$temp = array ();
		if (is_array ( $job_list ))
			foreach ( $job_list as $job )
				$temp [] = $job->id;
		$str_job_list = implode ( ',', $temp );
		return $str_job_list;
	
	}
	
	/** 
	 * Store configuration item
	 * @param array The post array
	 */
	
	function store() {
		global $jbconfig;
		$step = JRequest::getVar ( 'step', '' );
		$db = & JFactory::getDBO ();
		$user = JFactory::getUser ();
		$row = & $this->getItem ();
		
		$controller = JRequest::getVar ( 'view', 'jaapplications' );
		$post = JRequest::get ( 'request', JREQUEST_ALLOWHTML );
		$opt_attachment = JRequest::getVar ( 'opt_attachment' );
		
		foreach ( $post as $k => $value ) {
			if ($k != 'cid' && is_array ( $value )) {
				$post [$k] = implode ( ',', $value );
			}
			else{
				$post [$k] = trim($value);
			}
		}
		if (! $row->bind ( $post )) {
			echo "<script> alert('" . $row->getError ( null, true ) . "'); window.history.go(-1); </script>\n";
			return false;
		}
		if ($row->spec_field) {
			if (! assign_spec_field ( $controller, $row ))
				return false;
		}
		if ($row->editor_field)
			assign_editor_field ( $row );
		if ($row->opt_attachment == '1')
			$row->attachment = $this->attach_cv ( $row );
				
		if (! $row->check ()) {
			return false;
		}
		
		if (! ($temp = $row->store ())) 

		{
			
			echo "<script> alert('" . $row->getError ( null, true ) . "'); window.history.go(-1); </script>\n";
			return false;
		}
		
		return true;
	}
	
	function insertStrToStr($need, $str, $pos) {
		
		$str1 = substr ( $str, 0, $pos );
		$str2 = substr ( $str, $pos );
		$str1 .= $need;
		return $str1 . $str2;
	}
	
	function splitContent($str) {
		$line_length = 160;
		$strlen = strlen ( $str );
		$n = ceil ( $strlen / $line_length );
		$strpos = array ();
		
		$pos = 0;
		$strpos [] = 0;
		do {
			$pos = strpos ( $str, '<br', $pos + 1 );
			if ($pos)
				$strpos [] = $pos;
		
		} while ( $pos > 0 );
		$strpos [] = strlen ( $str );
		$arr_ins = array ();
		for($i = 0; $i < count ( $strpos ); $i ++) {
			
			if ($strpos [$i + 1] - $strpos [$i] > $line_length + 10) {
				for($j = 1; $j < ceil ( ($strpos [$i + 1] - $strpos [$i]) / $line_length ); $j ++) {
					$pos = strpos ( $str, ' ', $line_length * $j + $strpos [$i] );
					if ($pos > $line_length * $j + $strpos [$i] + 10)
						$pos = $line_length * $j + $strpos [$i];
					$arr_ins [] = $pos;
				
				}
			
			}
		
		}
		$str = '<br />' . $str;
		for($i = 0; $i < count ( $arr_ins ); $i ++)
			$str = JobBoardModelJAApplications::insertStrToStr ( '<br />', $str, $arr_ins [$i] + ($i + 1) * 6 );
		
		return $str;
	
	}
	
	function attach_cv($row) {
		$user = JFactory::getUser ( $row->user_id );
		$result = '';
		$resume = getItemByFieldName ( 'ja_resumes', 'user_id', $user->id );
		$resume = $resume [0];
		if ($resume->file_attachment) {
			$source_file = JPATH_ROOT . DS . $resume->file_attachment;
			$dest_file = str_replace ( 'resumes', 'applications', $source_file );
			if (! file_exists ( $dest_file ))
				copy ( $source_file, $dest_file );
			$result = str_replace ( 'resumes', 'applications', $resume->file_attachment );
		}
		return $result;
	}
	
	function increaseViews() {
		$item = $this->getItem ();
		$item->views ++;
		return $this->store ();
	}
	
	/**
	 * Remove field record
	 * @return Number of removed records
	 */
	function remove($task = 'remove') {
		$cid = JRequest::getVar ( 'cid', array (), 'request', 'array' );
		$n = count ( $cid );
		JArrayHelper::toInteger ( $cid );
		$user = &JFactory::getUser ();
		$backend_usertype = array (JBADMIN_USER, JBSUPERADMIN );
		
		$query = "DELETE FROM #__ja_applications WHERE id in ( " . implode ( ",", $cid ) . ')';
		$db = &JFactory::getDBO ();
		$db->setQuery ( $query );
		if ($db->query ())
			return $n;
		
		return 0;
	}
	
	function download() {
		$cid = JRequest::getVar ( 'cid', array (), 'post', 'array' );
		$n = count ( $cid );
		JArrayHelper::toInteger ( $cid );
		
		$item = $this->getItem ();
		$file_name = explode ( '/', $item->attachment );
		if ($item->id && $item->attachment) {
			$file = JPATH_SITE . DS . str_replace ( '/', '\\', $item->attachment );
			if (file_exists ( str_replace ( '/', '\\', $file ) ))
				$file = str_replace ( '/', '\\', $file );
			else
				$file = str_replace ( '\\', '/', $file );
			
			if ( ! file_exists($file) ){
        		echo JText::_("<script language='javascript'> alert('".JText::_("File not found on the Server")."'); </script>");
        		return ;
        	}
        	
            header('Content-Description: File Transfer');
		    header('Content-Type: application/octet-stream');
		    header('Content-Disposition: attachment; filename="'.substr ( $file_name [count ( $file_name ) - 1], 14 ) .'"');
		    header('Content-Transfer-Encoding: binary');
		    header('Expires: 0');
		    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
		    header('Pragma: public');
		    header('Content-Length: ' . filesize($file));
		    ob_clean();
		    flush();
		    readfile($file);
		}
	}
	
	function getUserIdFromJobId($job_id) {
		$db = JFactory::getDBO ();
		$query = "SELECT user_id FROM #__ja_jobs WHERE id='$job_id'";
		$db->setQuery ( $query );
		return $db->loadObject ();
	}
	
	function remove_attach() {
		remove_attach ( 'ja_applications' );
	
	}
}
?>